package com.creative.config;

import cn.dev33.satoken.exception.NotLoginException;
import com.creative.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

import static com.creative.constant.HttpStatus.UNAUTHORIZED;

/**
 * 网络异常建议
 * 创建人: ling
 * 创建时间: 2025/05/20
 */
@Slf4j
@RestControllerAdvice
public class WebExceptionAdvice {

    /**
     * 处理运行时异常
     *
     * @param e e
     * @return {@link AjaxResult }
     * @author ling
     * @date 2025/05/20
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult handleRuntimeException(RuntimeException e) {
        log.error("err异常：" + e.toString(), e);
        return AjaxResult.error("服务器异常 " + e.getMessage());
    }

    @ExceptionHandler(IOException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult handleIOException(IOException e) {
        log.error("err异常：" + e.toString(), e);
        return AjaxResult.error("服务器异常 " + e.getMessage());
    }


    /**
     * 处理NotLoginException异常
     *
     * @param nle NotLoginException
     * @return {@link AjaxResult }
     * @author ling
     * @date 2025/05/20
     */
    @ExceptionHandler(NotLoginException.class)
    public AjaxResult handlerNotLoginException(NotLoginException nle)
            throws Exception {
        // 打印堆栈，以供调试
//        nle.printStackTrace();

        // 判断场景值，定制化异常信息
        String message = "";
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未能读取到有效 token";
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token 无效";
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token 已过期";
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "token 已被顶下线";
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "token 已被踢下线";
        } else if (nle.getType().equals(NotLoginException.TOKEN_FREEZE)) {
            message = "token 已被冻结";
        } else if (nle.getType().equals(NotLoginException.NO_PREFIX)) {
            message = "未按照指定前缀提交 token";
        } else {
            message = "当前会话未登录";
        }
        // 返回给前端
        return AjaxResult.error(UNAUTHORIZED, message);
    }

}
